package sf01.studentmngmsystem.service.impl;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sf01.studentmngmsystem.entity.Student;
import sf01.studentmngmsystem.mapper.StudentMapper;
import sf01.studentmngmsystem.service.StudentService;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class StudentServiceImpl implements StudentService {
    
    @Autowired
    private StudentMapper studentMapper;
    
    @Override
    public Map<String, Object> getStudentsWithPagination(int page, int size, String name, String major, String classNumber, String sortField, String sortOrder) {
        int offset = (page - 1) * size;
    
        List<Student> students = studentMapper.findStudentsWithPagination(offset, size, name, major, classNumber, sortField, sortOrder);
    
        int total = studentMapper.countStudents(name, major, classNumber);
    
        int pages = (int) Math.ceil((double) total / size);
    
        Map<String, Object> result = new HashMap<>();
        result.put("records", students);
        result.put("total", total);
        result.put("pages", pages);
        result.put("current", page);
        result.put("size", size);
        
        return result;
    }
    
    @Override
    public Student getStudentById(Long id) {
        return studentMapper.findById(id);
    }
    
    @Override
    public List<Student> getStudentsByCondition(String name, String major, String classNumber) {
        return studentMapper.findByCondition(name, major, classNumber);
    }
    
    @Override
    @Transactional
    public void addStudent(Student student) {
        studentMapper.insert(student);
    }
    
    @Override
    @Transactional
    public void updateStudent(Student student) {
        studentMapper.update(student);
    }
    
    @Override
    @Transactional
    public void deleteStudent(Long id) {
        studentMapper.deleteById(id);
    }
    
    @Override
    public void batchDeleteStudents(List<Long> studentIds) {
        if (studentIds == null || studentIds.isEmpty()) {
            throw new IllegalArgumentException("学生ID列表不能为空");
        }
        
        for (Long studentId : studentIds) {
            studentMapper.deleteById(studentId);
        }
    }
    
    @Override
    @Transactional
    public void batchDeleteStudentsOptimized(List<Long> studentIds) {
        if (studentIds == null || studentIds.isEmpty()) {
            throw new IllegalArgumentException("学生ID列表不能为空");
        }
        
        // 使用单条SQL批量删除，性能更好
        studentMapper.batchDeleteByIds(studentIds);
    }
    
    @Override
    public int getTotalCount(String name, String major, String classNumber) {
        return studentMapper.countStudents(name, major, classNumber);
    }
    
    @Override
    public byte[] exportStudents(String name, String major, String classNumber) {
        List<Student> students = studentMapper.findAllForExport(name, major, classNumber);
        
        try (Workbook workbook = new XSSFWorkbook();
             ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            
            Sheet sheet = workbook.createSheet("学生信息");
            
            // 创建标题行
            Row headerRow = sheet.createRow(0);
            String[] headers = {"学生ID", "姓名", "性别", "出生日期", "专业", "班级编号", "入学日期", "联系电话", "电子邮箱", "家庭住址"};
            
            CellStyle headerStyle = workbook.createCellStyle();
            Font headerFont = workbook.createFont();
            headerFont.setBold(true);
            headerStyle.setFont(headerFont);
            headerStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
            headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
                cell.setCellStyle(headerStyle);
            }
            
            // 填充数据
            DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            for (int i = 0; i < students.size(); i++) {
                Row row = sheet.createRow(i + 1);
                Student student = students.get(i);
                
                row.createCell(0).setCellValue(student.getId());
                row.createCell(1).setCellValue(student.getName());
                row.createCell(2).setCellValue(student.getGender());
                row.createCell(3).setCellValue(student.getBirthDate() != null ? student.getBirthDate().format(dateFormatter) : "");
                row.createCell(4).setCellValue(student.getMajor());
                row.createCell(5).setCellValue(student.getClassNumber());
                row.createCell(6).setCellValue(student.getEnrollmentDate() != null ? student.getEnrollmentDate().format(dateFormatter) : "");
                row.createCell(7).setCellValue(student.getPhone() != null ? student.getPhone() : "");
                row.createCell(8).setCellValue(student.getEmail() != null ? student.getEmail() : "");
                row.createCell(9).setCellValue(student.getAddress() != null ? student.getAddress() : "");
            }
            
            // 自动调整列宽
            for (int i = 0; i < headers.length; i++) {
                sheet.autoSizeColumn(i);
            }
            
            workbook.write(out);
            return out.toByteArray();
            
        } catch (IOException e) {
            throw new RuntimeException("导出Excel文件失败", e);
        }
    }
    
    @Override
    public Student login(String account, String password) {
        // 根据邮箱或手机号查找学生
        Student student = studentMapper.findByEmailOrPhone(account);
        
        if (student != null) {
            // 直接比较数据库中的密码字段
            if (String.valueOf(student.getPassword()).equals(password)) {
                return student;
            }
        }
        return null;
    }
}


